package com.wisenet.service.wxpubno;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wisenet.common.Const;
import com.wisenet.common.WxConst;
import com.wisenet.dao.UserDAO;
import com.wisenet.dao.wx.ImageTextInfoDAO;
import com.wisenet.dao.wx.ImageTextMoreDAO;
import com.wisenet.dao.wx.KeysetDAO;
import com.wisenet.dao.wx.MessageInfoDAO;
import com.wisenet.dao.wx.UserInfoDAO;
import com.wisenet.entity.ImageTextInfo;
import com.wisenet.entity.ImageTextMore;
import com.wisenet.entity.Keyset;
import com.wisenet.entity.MessageInfo;
import com.wisenet.entity.UserInfo;
import com.wisenet.pojo.respmsgpojo.Music;
import com.wisenet.wx.api.GuessNumber;
import com.wisenet.wx.util.MessageManager;
import com.wisenet.wx.util.MessageUtil;
import com.wisenet.wx.util.StringUtil;
import com.wisenet.wx.util.WeixinUtil;

/**
 * 核心服务类
 * @author fzh
 */
@Service
public class FzhService {
	@Autowired
	UserDAO userDAO;
	@Autowired
	private KeysetDAO keysetDAO;
	@Autowired
	private UserInfoDAO userInfoDAO;
	@Autowired
	private MessageInfoDAO messageInfoDAO;
	@Autowired
	private ImageTextInfoDAO imageTextInfoDAO;
	@Autowired
	private ImageTextMoreDAO imageTextMoreDAO;
	
	@Value("${award_url}")
    private String awardUrl;
	@Value("${article_url}")
	private String articleUrl;
	@Value("${thumb_media_id}")
	private String thumbMediaId;
	
	// 日志
	public static Logger logger = Logger.getLogger(FzhService.class);
	
	/**
	 * 处理文本输入回复消息
	 * @param requestMap
	 * @return
	 * @throws Exception
	 */
	public String operateTextMessage(Map<String, String> requestMap) throws Exception {
		// 根据输入获取回复内容
		StringUtil.replyContent(requestMap);
		
		String respContent = requestMap.get("respContent");
		String toUserName = requestMap.get(WxConst.TO_USER_NAME);
		String fromUserName = requestMap.get(WxConst.FROM_USER_NAME);

		// 根据输入回复内容
		if (respContent != null) {
			return MessageUtil.replyTextMessage(fromUserName, toUserName, respContent);
		}

		// 关键词或记录功能消息
		if (Const.MENU_TYPE_RECORD.equals(requestMap.get(WxConst.TYPE))) {
			// 查询关键字回复（优先于其它上下行记录回复-20150323）
			respContent = replyMessageByKeyword(requestMap);
			if (respContent != null) return respContent;
			// 保存用户消息记录
			// saveMessageInfo(requestMap, null, null, null, "0");
		}
		
		// 根据用户最新的操作记录回复消息
		return replyMessageByType(requestMap);
	}
	
	/**
	 * 根据用户最新的操作记录回复消息
	 * @param requestMap
	 * @return
	 * @throws Exception 
	 */
	private String replyMessageByType(Map<String, String> requestMap) throws Exception {
		String respContent = null;
		String inputContent = requestMap.get(WxConst.CONTENT);
		String toUserName = requestMap.get(WxConst.TO_USER_NAME);
		String fromUserName = requestMap.get(WxConst.FROM_USER_NAME);
		
		// 查询用户记录
		UserInfo userInfo = userInfoDAO.getUserByUserId(fromUserName);
		if (userInfo == null) return null;

		String type = userInfo.getType();
		// 猜数 获取答案、回答次数及猜测提示
		if (Const.MENU_TYPE_GUESS_NUMBER.equals(type)) {
			if (userInfo.getIds() != null) {
				respContent = GuessNumber.getAnswer(inputContent, userInfo);
				// 更新猜数记录
				if (!Const.GUESS_NUMBER_WRONG.equals(userInfo.getContent())) {
					userInfoDAO.updateUser(userInfo);
				}
			}
		}
		
		// 发送翻译客服消息
		if (Const.MENU_TYPE_TRANSLATE_TO_EN.equals(type)
				|| Const.MENU_TYPE_TRANSLATE_TO_CH.equals(type)) {
			return null;
		}
		
		// 发送音乐客服消息
		if (Const.MENU_TYPE_SEARCH_MUSIC.equals(type)) {
			searchMusicList(inputContent, requestMap.get(WxConst.WX_TOKEN), fromUserName);
			return null;
		}
		
		// 发送聊天消息
		if (Const.MENU_TYPE_LETS_TALK.equals(type)) {
			respContent = ApiService.talk(inputContent);
		}
		
		return respContent != null ? 
				MessageUtil.replyTextMessage(fromUserName, toUserName, respContent) : null;
	}

	/**
	 * 发送客服消息
	 * @param openid
	 * @param content
	 * @param token
	 * @param msgType
	 */
	public void sendCustomMessage(String openid, String content, String token, String msgType) {
		String valueJson = content;
		if (MessageUtil.RESP_MESSAGE_TYPE_TEXT.equals(msgType)) {
			valueJson = String.format(WxConst.CUSTOM_MSG_TEXT, openid, content.replace("\"", "'").replace("\\", ""));
		}
		
		JSONObject message = JSON.parseObject(valueJson);
		
		JSONObject json = WeixinUtil.httpRequest(WxConst.CUSTOM_MSG_URL + token, "POST", message);
		if (json != null && json.getIntValue(WxConst.ERR_CODE) != 0) {
			logger.error("发送客服消息失败：" + json);
		}
	}

	/**
	 * 处理音频消息
	 * @param requestMap
	 * @return
	 * @throws Exception
	 */
	public String operateVoiceMessage(Map<String, String> requestMap) throws Exception {
		String toUserName = requestMap.get(WxConst.TO_USER_NAME);
		String fromUserName = requestMap.get(WxConst.FROM_USER_NAME);
		// 青云客聊天
		String respContent = ApiService.talk(requestMap.get("Recognition"));
		if (respContent == null) {
			respContent = "[撇嘴]我暂时还听不懂你说的话...";
		}
		return MessageUtil.replyTextMessage(fromUserName, toUserName, respContent);
	}

	/**
	 * 回复关键词消息
	 * @param requestMap
	 * @return
	 * @throws Exception
	 */
	private String replyMessageByKeyword(Map<String, String> requestMap) throws Exception {
		String inputContent = requestMap.get(WxConst.CONTENT);
		String toUserName = requestMap.get(WxConst.TO_USER_NAME);
		String fromUserName = requestMap.get(WxConst.FROM_USER_NAME);
		
		Keyset keySet = keysetDAO.findKeySet(toUserName, inputContent);
		if (keySet != null) {
			// 保存消息记录
//			saveMessageInfo(requestMap, null, null, null, "1");
			
			// 文本
			if (Const.MESSAGE_TYPE_TEXT.equals(keySet.getReType())) {
				return MessageUtil.replyTextMessage(fromUserName, toUserName, keySet.getRefText());
			}
			// 图文
			if (Const.MESSAGE_TYPE_IMAGE.equals(keySet.getReType())) {
				ImageTextInfo imageTextInfo = imageTextInfoDAO.findByPK(keySet.getRefImageTextId());
				if (imageTextInfo == null) return null;
				List<ImageTextMore> imagetextMoreList = null;
				if (Const.MESSAGE_TYPE_IMAGE.equals(imageTextInfo.getImageTextType())) {
					imagetextMoreList = imageTextMoreDAO.findImageTextMoreList(imageTextInfo.getImageTextNo());
				}
				return MessageManager.getImageTextInfo(requestMap, imageTextInfo, imagetextMoreList);
			}
		}
		return null;
	}
	
	/**
	 * 发送音乐客服消息
	 * @param name
	 * @param token
	 * @param fromUserName
	 * @throws Exception
	 */
	public void searchMusicList(String name, String token, String fromUserName) throws Exception {
		List<Music> musicList = ApiService.searchMusicList(name);
		
		if (CollectionUtils.isEmpty(musicList)) return;
		
		// 发送客服消息
		sendCustomMessage(fromUserName, "正在搜索中，预计10秒内完成...", token, MessageUtil.REQ_MESSAGE_TYPE_TEXT);
		
		for (Music music : musicList) {
			String content = String.format(WxConst.CUSTOM_MSG_MUSIC, fromUserName, 
					music.getTitle(), music.getMusicUrl(), music.getMusicUrl(), music.getDescription(), thumbMediaId);
			// 发送音乐客服消息
			sendCustomMessage(fromUserName, content, token, MessageUtil.RESP_MESSAGE_TYPE_MUSIC);
		}
	}
	
	
	
	public void saveMessageInfo(Map<String, String> requestMap, Long imageTextNo, String remsgType,
			String url, String keyword) {
		MessageInfo messageInfo = MessageManager.createMessageInfo(requestMap, imageTextNo, remsgType, url, keyword);
		messageInfoDAO.save(messageInfo);
	}
	
	public String getMovieNewsMessage(Map<String, String> requestMap, String title) throws Exception {
		ImageTextInfo imageTextInfo = imageTextInfoDAO.findByTitle(title);
		if (imageTextInfo == null) return null;
		String movieNames = imageTextInfoDAO.findTitles("gh_13381cc76c21");
		if (movieNames == null) return null;
		return MessageManager.getMovieNewsMessage(requestMap, imageTextInfo, movieNames);
	}
	
}
